package com.grj.park.boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grj.park.boot.domain.User;
import com.grj.park.boot.service.UserService;
import com.grj.park.boot.mapper.UserMapper;
import com.grj.park.boot.util.StringUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author eren
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-10-21 15:45:24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Page<User> fetchUserPage(int currentPage, int pageSize, User user, List<LocalDateTime> during) {
        QueryWrapper<User> userQueryWrapper = Wrappers.query();
        if (during != null && !during.isEmpty()) {
            userQueryWrapper.between("create_time", during.get(0), during.get(1));
        }
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(user);
        HashMap<String, Object> map = new HashMap<>();
        stringObjectMap.forEach((k, v) -> {
            if (v != null) {
                map.put(StringUtil.toCamelCase(k), v);
            }
        });
        userQueryWrapper.allEq(map, false);
        return baseMapper.selectPage(new Page<>(currentPage, pageSize), userQueryWrapper);
    }

    @Override
    public void postUser(User user) {
        baseMapper.insert(user);
    }

    @Override
    public void putUser(User user) {
        if(SecurityContextHolder.getContext().getAuthentication().getName().equals(user.getUsername()) && "0".equals(user.getStatus())){
            throw new RuntimeException("不能禁用自己:"+this.getClass().getName());
        }
        baseMapper.updateById(user);
    }

    @Override
    public void delUser(Long userId) {
        baseMapper.deleteById(userId);
    }

    @Override
    public void batchDelUser(List<Long> userIds) {
        System.out.println(userIds);
        baseMapper.deleteBatchIds(userIds);
    }

    @Override
    public User fetchUserById(Long userId) {
        return baseMapper.selectById(userId);
    }

    @Override
    public User getUserByUsername(String username) {
        return baseMapper.selectOne(Wrappers.<User>query().eq("username", username));
    }
}




